# gozerbot/persist.py
#
#

""" allow data to be written to disk in JSON format. creating the persisted 
    object restores data.
"""

__copyright__ = 'this file is in the public domain'

# gozerbot imports
from gozerbot.stats import stats
from gozerbot.utils.locking import lockdec
from gozerbot.utils.log  import rlog
from gozerbot.utils.trace import calledfrom
from gozerbot.utils.lazydict import LazyDict
from gozerbot.datadir import datadir
from google.appengine.ext import db

from simplejson import loads, dumps

# basic imports
import pickle, copy, sys, types

saving = []
stopsave = 0

class JSONindb(db.Model):
  filename = db.StringProperty(required=True)
  content = db.TextProperty()


class Persist(object):

    """ persist data attribute to JSON file. """

    def __init__(self, filename, default={}, init=True):

        """ Persist constructor """

        self.fn = unicode(filename) # filename to save to
        self.key = None
        try:
            self.obj = db.GqlQuery("SELECT * FROM JSONindb WHERE filename = :1", self.fn).get()
            if self.obj == None:
                self.obj = JSONindb(filename=self.fn, content=u"{}")
                self.data = default
                return
            else:
                jsontxt = self.obj.content

        except Exception, ex:
            raise
 
        self.data = loads(jsontxt)
        rlog(10, self.fn, 'loaded (%s)' % len(jsontxt))

    def listall(self):
        json = JSONindb.all()
        j = json.fetch(1000)
        names = []
        for i in j:
            names.append(i.filename)
        return names

    def init(self, default=None):

        """ initialize the data. """

        pass

    def save(self):

        if True:
            bla = dumps(self.data)
            jsondata = self.obj
            self.obj.content = bla
            key = self.obj.put()
            rlog(10, self.fn, 'saved (%s) key: %s' % (len(bla), key))

class PlugPersist(Persist):

    """ persist plug related data. """

    def __init__(self, filename, default=None):

        # retrieve plugname where object is constructed
        plugname = calledfrom(sys._getframe())

        # call base constructor with appropiate filename
        Persist.__init__(self, datadir + '/' + 'plugs' + '/' + plugname \
+ '/' + filename, default)


class LazyDictPersist(Persist):

    """ persisted lazy dict. """

    def __init__(self, default={}):

        # called parent constructor
        Persist.__init__(self)

        # if data not initialised set it to a LazyDict
        if not self.data:
            self.data = LazyDict(default)
